package vn.edu.hut.soict.translate.wordgraph;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

import org.apache.commons.lang3.StringEscapeUtils;

import vn.edu.hut.soict.automaton.State;
import vn.edu.hut.soict.automaton.Transition;

public class WordGraphWriter {
	public void write(WordGraph[][] graphs, String file) {
		BufferedWriter writer = null;

		try {
			writer = new BufferedWriter(new FileWriter(file));
			writer.write("<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?>\n");
			writer.write(String.format("<wordgraphs maxCW=\"%d\" maxFW=\"%d\">\n", graphs.length, graphs[0].length));
			for (int i = 0; i < graphs.length; i++) {
				for (int j = 0; j < graphs[i].length; j++) {
					if (graphs[i][j] != null) {
						writer.write(String.format("\t<wordgraph cW=\"%d\" fW=\"%d\">\n", i, j));
						writer.write("\t\t<states>\n");
						for (State<Word> s : graphs[i][j].getStates()) {
							writer.write(String.format("\t\t\t<state>%d</state>\n", s.getId()));
						}
						writer.write("\t\t</states>\n");
						writer.write("\t\t<transitions>\n");
						for (State<Word> s : graphs[i][j].getStates()) {
							for (Transition<Word> t : s.getNextTransitions()) {
								writer.write("\t\t\t<transition>\n");
								writer.write(String.format("\t\t\t\t<symbol pos=\"%s\">%s</symbol>\n", StringEscapeUtils.escapeXml(t.getSymbol().partOfSpeech()), StringEscapeUtils.escapeXml(t.getSymbol().getText())));
								writer.write(String.format("\t\t\t\t<source>%d</source>\n", t.getSource().getId()));
								writer.write(String.format("\t\t\t\t<target>%d</target>\n", t.getTarget().getId()));
								writer.write("\t\t\t</transition>\n");
							}
						}
						writer.write("\t\t</transitions>\n");
						writer.write("\t</wordgraph>\n");
					}
				}
			}
			writer.write("</wordgraphs>\n");
		}
		catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		if (writer != null) {
			try {
				writer.close();
			}
			catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
